package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/*
* 自动处理订单状态修改
* */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /*
    * 每隔两分钟自动查询待付款订单，超过十五分钟未支付的将其取消
    * */
    @Scheduled(cron = "0 */2 * * * ?")
    public void taskOrderOverTime() {
        log.info("开始查询待付款订单：{}", LocalDateTime.now());
        //查询符合该状态的订单
        Integer status = Orders.PENDING_PAYMENT;
        LocalDateTime orderTimeMax = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.selectOverTimeOrders(status, orderTimeMax);

        //修改订单状态信息
        if(ordersList != null && !ordersList.isEmpty()) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason(MessageConstant.ORDER_OVERTIME_AUTO_CANCEL);
                orderMapper.update(orders);
            }
        }
    }

    /*
    * 每天凌晨两点自动检查有无派送中订单，有则将其自动修改为已完成
    * */
    @Scheduled(cron = "0 0 2 * * ?")
    public void taskOrderInDelivery(){
        log.info("开始查询派送中订单：{}", LocalDateTime.now());
        //查询符合该状态的订单
        Integer status = Orders.DELIVERY_IN_PROGRESS;
        LocalDateTime orderTimeMax = LocalDateTime.now().plusMinutes(120);//检查上一工作日的所有订单
        List<Orders> ordersList = orderMapper.selectOverTimeOrders(status, orderTimeMax);

        //修改订单状态信息
        if(ordersList != null && !ordersList.isEmpty()) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);

                orderMapper.update(orders);
            }
        }

    }

}
